package com.tk.demo.dao.impl;

import com.tk.demo.dao.IAccountDao;
import com.tk.demo.model.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class IAccountDaoImpl implements IAccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int add(Account account) {
        int count = jdbcTemplate.update("insert into account(name, money) values(?, ?)",
                account.getName(),account.getMoney());
        return count;
    }

    @Override
    public int update(Account account) {
        int count = jdbcTemplate.update("update account set name = ?, money = ? where id = ?",
                account.getName(),account.getMoney(),account.getId());
        return count;
    }

    @Override
    public int delete(int id) {
        int count = jdbcTemplate.update("delete from account where id = ?", id);
        return 1;
    }

    @Override
    public Account findAccountById(int id) {
        List<Account> list = jdbcTemplate.query("select * from account where id =  ?", new Object[]{id}, new BeanPropertyRowMapper<>(Account.class));
        if (list != null && list.size() > 0) {
            return  list.get(0);
        }
        return null;
    }

    @Override
    public List<Account> findAccountList() {
        List<Account> accounts = jdbcTemplate.query("select * from account", new Object[0],new BeanPropertyRowMapper<>(Account.class));
        if (accounts != null && accounts.size() > 0) {
            return accounts;
        }
        return new ArrayList<>();
    }
}
